package com.demo.bookstore.service.impl;

import com.demo.bookstore.bean.*;
import com.demo.bookstore.dao.impl.OrderItemDaoImpl;
import com.demo.bookstore.dao.OrderDao;
import com.demo.bookstore.dao.OrderItemDao;
import com.demo.bookstore.dao.impl.OrderDaoImpl;
import com.demo.bookstore.service.OrderService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author ddone
 * @date 2024/3/17-10:19
 */
public class OderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDao = new OrderItemDaoImpl();
    @Override
    public String addOrder(Cart cart, User user) {
        String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String orderNo = System.currentTimeMillis() + "";
        BookOrder bookOrder = BookOrder.builder()
                .orderNo(orderNo)
                .createTime(createTime)
                .orderStatus(0)
                .totalCount(cart.getTotalCount())
                .totalAmount(cart.getTotalAmount())
                .userId(user.getUserid())
                .build();
        // 添加订单
        orderDao.addOrder(bookOrder);

        // 添加订单Item
        int orderId = orderDao.findOrderId(orderNo);

        cart.getItemList().forEach(item->{
            Book book = item.getBook();
            BookOrderItem bookOrderItem = BookOrderItem
                    .builder()
                    .orderId(orderId)
                    .bookName(book.getTitle())
                    .imgPath(book.getImgPath())
                    .itemAmount(item.getAmount())
                    .price(book.getPrice())
                    .itemCount(item.getCount())
                    .createTime(createTime)
                    .build();
            orderItemDao.addOrderItem(bookOrderItem);
        });
        return orderNo;
    }

    @Override
    public List<BookOrder> findOrderByUserId(int userId) {
        return orderDao.findOrderByUserId(userId);
    }
}
